import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { passengerAPI } from '../../services/api';

export const fetchPassengers = createAsyncThunk(
  'passengers/fetchPassengers',
  async (params = {}) => {
    const response = await passengerAPI.getAllPassengers(params);
    return response.data;
  }
);

export const fetchPassengerById = createAsyncThunk(
  'passengers/fetchPassengerById',
  async (id) => {
    const response = await passengerAPI.getPassengerById(id);
    return response.data;
  }
);

export const createPassenger = createAsyncThunk(
  'passengers/createPassenger',
  async (passengerData) => {
    const response = await passengerAPI.createPassenger(passengerData);
    return response.data;
  }
);

export const updatePassenger = createAsyncThunk(
  'passengers/updatePassenger',
  async ({ id, data }) => {
    const response = await passengerAPI.updatePassenger(id, data);
    return response.data;
  }
);

export const deletePassenger = createAsyncThunk(
  'passengers/deletePassenger',
  async (id) => {
    await passengerAPI.deletePassenger(id);
    return id;
  }
);

const passengerSlice = createSlice({
  name: 'passengers',
  initialState: {
    passengers: [],
    currentPassenger: null,
    loading: false,
    error: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
    },
  },
  reducers: {
    clearCurrentPassenger: (state) => {
      state.currentPassenger = null;
    },
    clearError: (state) => {
      state.error = null;
    },
    setPagination: (state, action) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchPassengers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchPassengers.fulfilled, (state, action) => {
        state.loading = false;
        state.passengers = action.payload.passengers || action.payload;
        state.pagination.total = action.payload.total || action.payload.length;
      })
      .addCase(fetchPassengers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message;
      })
      .addCase(createPassenger.fulfilled, (state, action) => {
        state.passengers.unshift(action.payload);
      })
      .addCase(updatePassenger.fulfilled, (state, action) => {
        const index = state.passengers.findIndex(p => p.id === action.payload.id);
        if (index !== -1) {
          state.passengers[index] = action.payload;
        }
      })
      .addCase(deletePassenger.fulfilled, (state, action) => {
        state.passengers = state.passengers.filter(p => p.id !== action.payload);
      });
  },
});

export const { clearCurrentPassenger, clearError, setPagination } = passengerSlice.actions;
export default passengerSlice.reducer;